package com.lhc.bean.postprocessorinterface;

import com.lhc.annotation.MyService;
import com.lhc.bean.PostProcessorRegistryBean;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Component;

/**
 * @author LuHuanCheng
 * 类说明：测试BeanDefinitionRegistryPostProcessor接口实现类的调用  在bean实例化之前
 */
@Component
public class CustomerBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {

    //这个方法可以对beanDefinition做增删改查
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        System.out.println("进入BeanDefinitionRegistryPostProcessor接口的实现类的postProcessBeanDefinitionRegistry方法");

        //查询所有beanDefinition
        String[] beanDefinitionNames = registry.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
//            System.out.println("beanDefinitionName：" + beanDefinitionName);
        }

        //创建beanDefinition，这里有实例化 applicationContext.get("name")可以拿到
        GenericBeanDefinition genericBeanDefinition = new GenericBeanDefinition();
        genericBeanDefinition.setBeanClass(PostProcessorRegistryBean.class);
        MutablePropertyValues propertyValues = genericBeanDefinition.getPropertyValues();
        propertyValues.addPropertyValue("name", "i am BeanDefinitionRegistryPostProcessor");
        registry.registerBeanDefinition("postProcessorRegistryBean", genericBeanDefinition);


        //扫描有自定义注解的类并实例化
        ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(registry);
        scanner.addIncludeFilter(new AnnotationTypeFilter(MyService.class));
        scanner.scan("com.lhc.bean");

    }

    //这个方法可以拿到容器对象
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

        System.out.println("进入BeanDefinitionRegistryPostProcessor接口的实现类的postProcessBeanFactory方法");

        //beanFactory可以强转为beanRegistry
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
        String[] beanDefinitionNames = registry.getBeanDefinitionNames();
        System.out.println("beanDefinitionNames个数：" + beanDefinitionNames.length);
    }
}